import React from "react";
// 导入antd css样式
import "antd/dist/antd.css";
// import { Button, Tooltip } from "antd";
import {
  Button,
  Select,
  Checkbox,
  Radio,
  Row,
  Col,
  Tabs,
  Table,
  Space,
  List,
  Avatar,
  Alert,
  message,
  Modal,
  Form,
  Input,
  DatePicker,
  Switch,
  InputNumber,
  Cascader,
} from "antd";
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined,
  MinusOutlined,
} from "@ant-design/icons";

const { TabPane } = Tabs;

const { Option } = Select;

function handleChangeBySelect(value) {
  console.log(`selected ${value}`);
}

function onChangeByCheckbox(e) {
  console.log(`checked =  ${e.target.checked}`);
}

function onRadio(e) {
  console.log(`get = ${e.target.value}`);
}

function onChangeByTabs(key) {
  console.log(key);
}

function onChangeDatePicker(date, dateString) {
  console.log(date, dateString);
}

const columns = [
  {
    title: "姓名",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "年龄",

    dataIndex: "age",
    key: "age",
  },
  {
    title: "住址",
    dataIndex: "address",
    key: "address",
  },
  {
    title: "操作",
    dataIndex: "operation",
    key: "operation",
  },
];

// 作为唯一key
let count = 2;

const nameArr = ["Lucy", "Leo", "Jhon", "Frank", "Leo"];


 // const useMemo = React.useMemo;
  // const useCallback = React.useCallback;
const useState = React.useState;

const list = {
  UnitList: [
    { value: 1, name: "克" },
    { value: 2, name: "份" },
  ],
  StandardList: [
  {
    label: "辣度",
    value: "1",
    children: [
      { label: "微辣", value: "0" },
      { label: "中辣", value: "1" },
      { label: "超辣", value: "2" },
      { label: "麻辣", value: "3" },
      { label: "酸辣", value: "4" },
    ],
    }],
  PlaceList: [
  { value: 0, name: "北京", sname: "beijing" },
  { value: 1, name: "上海", sname: "shanghai" },
  { value: 2, name: "广州", sname: "guangzhou" },
  { value: 3, name: "深圳", sname: "shenzhen" },
  { value: 4, name: "成都", sname: "chengdu" },
]
};

const DataParse = (values) => {
  // 拼接
  const newStandard = values.Standard[0] + values.Standard[1];
  values.standard = newStandard;
  return values;
};




const GetAntD = () => {

  const [unitVisible, setUnitVisible] = useState(true);

  const [formData, setFormData] = useState({});
  
  const onSearch = (values) => {
    // values = DataParse(values);
    console.log(values);
    setFormData({ values });
  };

   const onFinishFailed = (errorInfo) => {
     console.log(`Faild：${errorInfo}`);
   };

  const [form] = Form.useForm();

  // 使用到的数据源
  const [TabData, setTabData] = React.useState([
    {
      key: -3,
      name: "胡彦斌",
      age: 22,
      address: "北京市海淀区",
      operation: (
        <Button
          type="link"
          onClick={() => {
            Modal.info({
              title: "测试模态框",
              content: "我出来了哟",
            });
          }}
        >
          查看
        </Button>
      ),
      render: (text, record, index) => {
        console.log(text, record, index);
      }
    },
  ]);

  const [ListData, setListData] = React.useState([
    {
      title: "星期一",
      desc: "I want to play",
    },
    {
      title: "星期二",
      desc: "I want to play",
    },
  ]);

  const nameArr = ["", "", "", "Lucy", "Leo", "Jhon", "Frank", "Leo"];
  const handleAddOrSub = React.useCallback(
    (oper) => {
      if (oper === 1) {
        const newData = [].concat(TabData);
        newData.push({
          key: count++,
          name: nameArr[count],
          age: 22,
          address: "北京市海淀区",
          render: (text, record, index) => {
            console.log(text, record, index);
          },
          operation: (
            <Button
                type="link"
                onClick={() => {
                  Modal.info({
                    title: "测试模态框",
                    content: `我出来了哟`,
                  });
                }}
              >
                查看
              </Button>
          ),
        });
        if (newData && newData.length > 5) {
          message.warning("最多添加5条！");
          // 避免重复弹出
          message.config({
            top: 100,
            duration: 2,
            maxCount: 3,
            rtl: true,
            prefixCls: "my-message",
          });
          return;
        }
        setTabData(newData);
      } else if (oper === 2) {
        TabData.pop();
        setTabData([].concat(TabData));
      }
    },
    [TabData]
  );

  const data = [
    {
      title: "Ant Design Title 1",
    },
    {
      title: "Ant Design Title 2",
    },
    {
      title: "Ant Design Title 3",
    },
    {
      title: "Ant Design Title 4",
    },
  ];

  // 表单综合练习
  // 表单综合练习点击事件
  const handleBySubmit = () => {
    Modal.info({
      title: "表单信息",
      content: "我来了",
    });
  };


  return (
    <div>
      <h1>AntD入门</h1>
      <div>
        <Space>
          <Button type="primary" icon={<SearchOutlined />}>
            查询
          </Button>
          <Button icon={<RedoOutlined />}>重置</Button>
        </Space>
      </div>
      <br />
      <div>
        <Select
          defaultValue="Lucy"
          style={{ width: 120 }}
          onChange={handleChangeBySelect}
        >
          <Option value="jack">Jack</Option>
          <Option value="jucy">Lucy</Option>
          <Option value="disabled" disabled>
            Disabled
          </Option>
          <Option value="xiaoming">Xiaoming</Option>
        </Select>
      </div>
      <br />
      <div>
        <Checkbox onChange={onChangeByCheckbox} checked={true}>
          basketball
        </Checkbox>
        <Checkbox onChange={onChangeByCheckbox}>football</Checkbox>
        <Checkbox onChange={onChangeByCheckbox}>soccerball</Checkbox>
      </div>
      <br />
      <div>
        <Radio.Group onChange={onRadio} value={1}>
          <Radio value={1}>中文</Radio>
          <Radio value={2}>英文</Radio>
        </Radio.Group>
      </div>
      <br />
      <div>
        <Tabs defaultActiveKey="1" onChange={onChangeByTabs}>
          <TabPane tab="Tab 1" key="1">
            <Row>
              <Col span={3}>
                <Button type="dashed" icon={<SearchOutlined />}>
                  查看
                </Button>
                <br />
                <Button icon={<SearchOutlined />}>查看</Button>
                <br />
                <Button icon={<SearchOutlined />}>查看</Button>
              </Col>
              <Col span={3}>
                <Button icon={<RedoOutlined />}>重置</Button>
                <br />
                <Button icon={<RedoOutlined />}>重置</Button>
                <br />
                <Button icon={<RedoOutlined />}>重置</Button>
              </Col>
            </Row>
          </TabPane>

          <TabPane tab="Tab 2" key="2">
            <h3>表格1</h3>
            <Alert message="最多为员工表添加5条数据" type="info" />
            <br />
            <Space>
              <Button
                size=""
                onClick={() => {
                  handleAddOrSub(1);
                }}
                icon={<PlusOutlined />}
              >
                新增
              </Button>
              <Button
                size=""
                onClick={() => {
                  handleAddOrSub(2);
                }}
                icon={<MinusOutlined />}
              >
                删除
              </Button>
            </Space>
            <Table dataSource={TabData} columns={columns} />
          </TabPane>

          <TabPane tab="Tab 3" key="3">
            {/* <Space>
              <Button
                size=""
                onClick={() => {
                  handleAddOrSub(3);
                }}
              >
                +新增
              </Button>
              <Button
                size=""
                onClick={() => {
                  handleAddOrSub(4);
                }}
              >
                -删除
              </Button>
            </Space> */}
            <List
              itemLayout="horizontal"
              dataSource={data}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
                    title={<a href="https://ant.design">{item.title}</a>}
                    description="Ant Design, a design language for background applications, is refined by Ant UED Team"
                  />
                </List.Item>
              )}
            />
            ,
            {/* <List
              itemLayout="horizontal"
              dataSource={ListData}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={
                      <Avatar src="https://joeschmoe.io/api//v1/random" />}
                    title={<a href="https://ant.design">{item.title}</a>}
                    description={item.desc}
                  />
                </List.Item>
              )}
            /> */}
          </TabPane>
          <TabPane tab="Tab 4" key="4">
            <Form
              name="test"
              onFinish={(values) => {
                console.log(values);
              }}
              onFinishFailed={(values, errorFields, outofDate) => {
                console.log(values, errorFields, outofDate);
              }}
            >
              <Form.Item
                label="账号"
                name="username"
                rules={[
                  {
                    required: true,
                    message: "请输入用户名",
                  },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="密码"
                name="password"
                rules={[
                  {
                    required: true,
                    message: "请输入用户名",
                  },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item>
                <Button htmlType="submit">提交</Button>
              </Form.Item>
            </Form>
          </TabPane>
          <TabPane tab="Tab 5" key="5">
            <DatePicker onChange={onChangeDatePicker} />
            <DatePicker onChange={onChangeDatePicker} picker="week" />
            <DatePicker onChange={onChangeDatePicker} picker="month" />
            <DatePicker onChange={onChangeDatePicker} picker="quarter" />
            <DatePicker onChange={onChangeDatePicker} picker="year" />
          </TabPane>
          <TabPane tab="Tab 6" key="6">
            <Form
              labelCol={{
                span: 4,
              }}
              wrapperCol={{
                span: 14,
              }}
              form={form}
              name="basic"
              layout="horizontal"
              initialValues={{}}
              onFinish={(values) => {
                onSearch(values);
              }}
              onFinishFailed={onFinishFailed}
              onValuesChange={(changed, all) => {
                if (changed && changed.weight === "0") {
                  form.resetFields(["unit"]);
                  setUnitVisible(false);
                } else {
                  setUnitVisible(true);
                }
              }}
            >
              <Form.Item label="商品类型" name="weight">
                <Radio.Group>
                  <Space>
                    <Radio.Button value="1">称重</Radio.Button>
                    <Radio.Button value="0">非称重</Radio.Button>
                  </Space>
                </Radio.Group>
              </Form.Item>
              <Form.Item
                label="名称"
                name="name"
                required={true}
                rules={[
                  {
                    max: 10,
                    min: 1,
                    message: "长度为1~10",
                  },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="售卖价格"
                name="salePrice"
                dependencies={["costPrice"]}
                required={true}
                rules={[
                  {
                    type: "number",
                    max: 99,
                    min: 1,
                    message: "大小为1~99",
                  },
                  // getFieldValue 获取表单区域的值
                  ({ getFieldValue }) => ({
                    // value 是当前项的值
                    validator(_, value) {
                      // if (!value || getFieldValue("salePrice") < value) {
                      if (getFieldValue("costPrice") < value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(
                        new Error("售卖价格须大于成本价格")
                      );
                    },
                  }),
                ]}
              >
                <InputNumber />
              </Form.Item>
              <Form.Item
                label="成本价格"
                name="costPrice"
                dependencies={["salePrice"]}
                required={true}
                rules={[
                  {
                    type: "number",
                    max: 99,
                    min: 1,
                    message: "大小为1~99",
                  },
                  // getFieldValue 获取表单区域的值
                  ({ getFieldValue }) => ({
                    // value 是当前项的值
                    validator(_, value) {
                      // if (!value || getFieldValue("salePrice") < value) {
                      if (getFieldValue("salePrice") > value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(
                        new Error("成本价格须小于售卖价格")
                      );
                    },
                  }),
                ]}
              >
                <InputNumber />
              </Form.Item>
              {unitVisible ? (
                <Form.Item label="单位" name="unit">
                  <Select>
                    {list.UnitList.map((unit) => {
                      return (
                        <Select.Option value={unit.name} key={unit.value}>
                          {unit.name}
                        </Select.Option>
                      );
                    })}
                  </Select>
                </Form.Item>
              ) : null}
              <Form.Item label="多级规格" name="standard" required={true}>
                <Cascader options={list.StandardList} />
              </Form.Item>
              <Form.Item label="生产地" name="producePlace">
                <Select placeholder="Please Select">
                  {list.PlaceList.map((place) => {
                    return (
                      <Select.Option
                        value={place.sname}
                        name={place.name}
                        key={place.value}
                      >
                        {place.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
              <Form.Item
                label="生产日期"
                // name="produceDate"
              >
                <DatePicker />
              </Form.Item>
              <Form.Item
                label="打包个数"
                name="count"
                rules={[
                  {
                    type: "number",
                    // max: 99,
                    min: 1,
                    message: "",
                  },
                  // getFieldValue 获取表单区域的值
                  ({ getFieldValue }) => ({
                    // value 是当前项的值
                    validator(_, value) {
                      // if (!value || getFieldValue("salePrice") < value) {
                      if (getFieldValue("salePrice") && value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(
                        new Error("成本价格须小于售卖价格")
                      );
                    },
                  }),
                ]}
              >
                <InputNumber />
              </Form.Item>
              <Form.Item label="参与优惠">
                <Switch />
              </Form.Item>

              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button
                  type="primary"
                  htmlType="submit"
                  onClick={handleBySubmit}
                >
                  提交信息
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </div>
      <br />
      <div></div>
    </div>
  );
};

export default GetAntD;
